#include <sstream>
#include <SypX/SypX.h>

#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif

#include "MissionScene.h"
#include "SelectionScene.h"
#include "GameScene.h"
#include "SheepDefenceApp.h"

namespace SheepDefence
{
	SelectionScene::SelectionScene(SypX::Font* f, int level, mission& stats) : level(level), stats(stats)
	{
		font = f;
	}

	SelectionScene::~SelectionScene(void)
	{
		delete bg;

		for (unsigned int i = 0; i < 3; i++)
			delete dogs[i];

		delete back;
		
		engine->getAudioEngine()->deleteSoundBuffer(snd);
		
	}

	void SelectionScene::init()
	{
		
		engine = SypX::Engine::getSingleton();
		render = engine->getRenderer();
		canvas = engine->getCanvas();	
		if(!font)
		{
			font = engine->loadFontFromFile("Fonts/sheepFont.ttf", 24, 3);
		}

		bgMesh = new SypX::Mesh();
		bgMesh->initAsQuad(320.0f,480.0f);
		
		bgTex = SypX::Texture::loadFromFile("Textures/bgSelection.png");
		
		bg = new SypX::MeshInstance();
		bg->useMesh(bgMesh);
		bg->useTexture(bgTex);
		
		bg->setPosition(SypX::Vec2(160.0f, 240.0f));		

		render->setClearScreenColor(SypX::Vec4(0.0f, 0.0f, 0.0f, 1.0f));		
		
		snd = engine->getAudioEngine()->loadFromWAVFile("Sounds/Sega.wav");
		//engine->getAudioEngine()->playSound(snd, SypX::Vec3()) ;

		backTex = SypX::Texture::loadFromFile("Textures/btnBack.png");
		back = new SypX::Button(160.0f, 80.0f, 80.0f, 30.0f, 0.9f, backTex);
		back->onDownCallBack = SYPXBIND(&SelectionScene::goBack, this, SYPX_ARG1, SYPX_ARG2);

		dogTex[0] = SypX::Texture::loadFromFile("Textures/terrierLarge.png");
		dogTex[1] = SypX::Texture::loadFromFile("Textures/collieLarge.png");
		dogTex[2] = SypX::Texture::loadFromFile("Textures/greyhoundLarge.png");

		for (unsigned int i = 0; i < 3; i++)
		{
			dogs[i] = new SypX::Button(160.0f, 340.0f - 90.0f * i, 75.0f, 75.0f, 0.9f, dogTex[i]);
			dogs[i]->onDownCallBack = SYPXBIND(&SelectionScene::goPlay, this, SYPX_ARG1, SYPX_ARG2);
		}
	}

	void SelectionScene::handleInput()
	{
		SypX::Event e = canvas->getEvent();
		
		if (back->processInput(e))
			return;

		
		for (unsigned int i = 0; i < 3; i++)
			if (dogs[i]->processInput(e))
				return;
	}

	void SelectionScene::run()
	{
		render->clearScreen();		
		render->setActiveColor(SypX::Vec4(1.0f,1.0f,1.0f,1.0f));
		render->drawMesh(bg);
		handleInput();

		for (unsigned int i = 0; i < 3; i++)
			dogs[i]->draw();

		back->draw();
		
		canvas->swapBuffers();
		//changeScene(new GameScene(font));
	}

	void SelectionScene::goBack(SypX::GuiComponent* g, SypX::Event& e)
	{
		changeScene(new MissionScene(font, level));
	}

	void SelectionScene::goPlay(SypX::GuiComponent* g, SypX::Event& e)
	{
		for (unsigned int i = 0; i < 3; i++)
			if (dogs[i] == g)
				changeScene(new GameScene(font, level, i, stats.scores[i]));
	}
}
